<template>
  <el-dialog
    :model-value="dialogDetails"
    width="40%"
    title="视频详情"
    :before-close="handleClose"
  >
    <div
      v-loading="loading"
      element-loading-text="加载中..."
      class="dialog-content"
    >
      <el-divider />
      <!-- 添加表单内容 -->
      <el-form :model="form" label-width="120px">
        <el-form-item label="视频名称：" prop="title">
          <el-input v-model="form.title" disabled />
        </el-form-item>

        <el-form-item label="封面图片：" prop="coverUrl">
          <div class="image-preview" v-if="form.coverUrl">
            <img :src="form.coverUrl" class="preview-image" />
          </div>
          <div class="no-image" v-else>暂无图片</div>
        </el-form-item>
        <el-form-item label="视频介绍：" prop="videoIntro">
          <div class="readonly-content" v-html="form.videoIntro"></div>
        </el-form-item>

        <el-form-item label="视频来源：">
          <el-tabs v-model="videoSource" class="video-source-tabs">
            <el-tab-pane label="本地视频" name="0">
              <div class="video-input-box">
                <el-input
                  v-model="form.url"
                  placeholder="视频URL"
                  readonly
                  v-show="videoSource === '0'"
                  disabled
                />
                <div v-if="form.url && videoSource === '0'" class="video-info">
                  <div class="video-file">
                    <el-icon class="video-icon"><VideoPlay /></el-icon>
                    <span class="video-name">{{ videoName }}</span>
                  </div>
                  <el-button
                    type="primary"
                    link
                    @click="handlePreviewVideo(form.url)"
                  >
                    预览视频
                  </el-button>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="b站视频" name="1">
              <div class="video-input-box">
                <el-input
                  v-model="biliVideo.biliId"
                  placeholder="请输入BV号，例如：BV1GJ411x7h7"
                  readonly
                  v-show="videoSource === '1'"
                  disabled
                />
                <div
                  v-if="biliVideo.biliUrl && videoSource === '1'"
                  class="video-info"
                >
                  <div class="video-file">
                    <el-icon class="video-icon"><VideoPlay /></el-icon>
                    <span class="video-name">{{ biliVideo.biliId }}</span>
                  </div>
                  <el-button
                    type="primary"
                    link
                    @click="handlePreviewBiliVideo(biliVideo.biliId)"
                  >
                    预览视频
                  </el-button>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>

        <el-form-item label="发布状态：" prop="releaseStatus">
          <el-select v-model="form.releaseStatus" disabled>
            <el-option label="草稿" :value="0" />
            <el-option label="已发布" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="空间名称：" prop="spaceIdList">
          <el-select v-model="form.spaceIdList" multiple disabled>
            <el-option
              v-for="item in form.spaceNameList"
              :key="item.spaceId"
              :label="item.name"
              :value="item.spaceId"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">关闭</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加视频预览对话框 -->
  <el-dialog
    v-model="previewVisible"
    :title="previewTitle"
    width="60%"
    :before-close="handlePreviewClose"
    append-to-body
    destroy-on-close
  >
    <div class="video-preview-container">
      <template v-if="videoSource === '0'">
        <video
          v-if="previewUrl"
          :src="previewUrl"
          controls
          class="preview-video"
        >
          您的浏览器不支持 video 标签。
        </video>
      </template>
      <template v-else>
        <iframe
          v-if="previewUrl"
          :src="`https://player.bilibili.com/player.html?bvid=${previewUrl}`"
          class="preview-iframe"
          frameborder="no"
          framespacing="0"
          scrolling="no"
          allowfullscreen="true"
        ></iframe>
      </template>
    </div>
  </el-dialog>
</template>

<script setup title="DetailsFacilityDialog">
import { ref, watch } from 'vue';
import { getVideoDetails } from '@/api/Venue/video';
import { VideoPlay } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
  dialogDetails: {
    type: Boolean,
  },
  DetailsVideoId: {
    type: String,
  },
});

const emit = defineEmits(['cancel']);
const loading = ref(false);
// 添加视频来源变量
const videoSource = ref('0');

// 修改表单初始化数据
const initialForm = {
  title: '',
  coverUrl: '',
  url: '',
  releaseStatus: '',
  videoIntro: '',
  spaceIdList: [],
  spaceNameList: [],
  mediaType: 0, // 添加 mediaType 字段
};

const form = ref({ ...initialForm });

// 重置表单数据
const resetForm = () => {
  form.value = { ...initialForm };
  videoName.value = '';
  biliVideo.value = {
    biliId: '',
    biliUrl: '',
  };
  videoSource.value = '0';
};

// 添加B站视频相关数据
const biliVideo = ref({
  biliId: '',
  biliUrl: '',
});

// 添加视频名称
const videoName = ref('');

// 添加预览相关的响应式变量
const previewVisible = ref(false);
const previewUrl = ref('');
const previewTitle = ref('视频预览');

// 修改获取详情数据的处理
const getFacilityData = async (id) => {
  if (!id) return;
  loading.value = true;
  try {
    // 先重置所有数据
    resetForm();

    const res = await getVideoDetails(id);
    if (res.data.code === 200 && res.data.data) {
      const details = res.data.data;

      // 根据 mediaType 设置视频来源和 URL
      videoSource.value = details.mediaType === 1 ? '1' : '0';

      // 设置基本表单数据
      form.value = {
        title: details.title || '',
        coverUrl: details.coverUrl || '',
        videoIntro: details.videoIntro || '',
        releaseStatus: Number(details.releaseStatus),
        spaceIdList: details.spaceVOList || [],
        spaceNameList: details.spaceVOList || [],
        mediaType: details.mediaType,
      };

      // 根据 mediaType 处理视频 URL
      if (details.mediaType === 1) {
        // B站视频
        biliVideo.value = {
          biliId: details.url,
          biliUrl: details.url,
        };
        form.value.url = ''; // 清空本地视频 URL
      } else {
        // 本地视频
        form.value.url = details.url || '';
        if (details.url) {
          const urlParts = details.url.split('/');
          videoName.value = urlParts[urlParts.length - 1];
        }
        // 清空 B 站视频数据
        biliVideo.value = {
          biliId: '',
          biliUrl: '',
        };
      }
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情失败');
  } finally {
    loading.value = false;
  }
};

// 监听弹窗和ID变化
watch(
  [() => props.dialogDetails, () => props.DetailsVideoId],
  ([newDialog, newId], [oldDialog]) => {
    if (newDialog && newId) {
      getFacilityData(newId);
    } else if (!newDialog && oldDialog) {
      // 关闭弹窗时重置数据
      resetForm();
    }
  }
);

// 处理取消按钮的点击事件
const handleCancel = () => {
  emit('cancel');
};

// 关闭对话框
const handleClose = () => {
  handleCancel();
};

// 获取B站视频BV号
const getBiliId = (url) => {
  if (!url) return '';
  const match = url.match(/bvid=([^&]+)/);
  return match ? match[1] : '';
};

// 获取本地视频文件名
const getFileName = (url) => {
  if (!url) return '';
  const urlParts = url.split('/');
  return urlParts[urlParts.length - 1];
};

// 处理本地视频预览
const handlePreviewVideo = (url) => {
  previewUrl.value = url;
  previewTitle.value = '本地视频预览';
  previewVisible.value = true;
};

// 修改 B 站视频预览处理函数
const handlePreviewBiliVideo = (bvid) => {
  if (!bvid) {
    ElMessage.warning('视频ID不能为空');
    return;
  }
  // 如果 bvid 包含完整 URL，提取 BV 号
  const bvidMatch = bvid.match(/BV[\w]+/);
  previewUrl.value = bvidMatch ? bvidMatch[0] : bvid;
  previewTitle.value = 'B站视频预览';
  previewVisible.value = true;
};

// 处理预览对话框关闭
const handlePreviewClose = () => {
  previewVisible.value = false;
  previewUrl.value = '';
};
</script>

<style lang="scss" scoped>
.dialog-content {
  position: relative;
  min-height: 100px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.image-preview {
  width: 120px;
  height: 120px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
  }
}
.video-input-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;

  .video-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;

    .video-file {
      display: flex;
      align-items: center;
      gap: 8px;

      .video-icon {
        color: #409eff;
        font-size: 16px;
      }

      .video-name {
        color: #606266;
        font-size: 14px;
      }
    }

    .delete-icon {
      color: #f56c6c;
      font-size: 16px;
      cursor: pointer;

      &:hover {
        color: #f78989;
      }
    }
  }

  :deep(.el-input-group__append) {
    padding: 0;
    background-color: transparent;
    border: none;

    .upload-button {
      .el-upload {
        display: block;
        line-height: 1;
      }

      .el-button {
        border: none;
        padding: 0 15px;
        margin: 0;
      }
    }
  }

  :deep(.el-input__wrapper) {
    height: 32px;
    line-height: 32px;
  }
}
.no-image {
  width: 120px;
  height: 120px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}

.upload-box,
.upload-placeholder,
.delete-icon {
  display: none;
}

.readonly-content {
  padding: 12px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 200px;
  width: 100%;
  overflow-y: auto;
  line-height: 1.5;
  color: #606266;

  :deep(p) {
    margin: 0;
    padding: 0;
  }

  :deep(img) {
    max-width: 100%;
  }
}

// 调整表单项宽度
:deep(.el-form-item__content) {
  width: calc(100% - 120px);
}

.video-source-tabs {
  width: 100%;

  :deep(.el-tabs__content) {
    width: 100%;
  }

  :deep(.el-tab-pane) {
    width: 100%;
  }

  .video-input-box,
  .video-info {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 8px;

    .video-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 6px 12px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .video-file {
        display: flex;
        align-items: center;
        gap: 6px;

        .video-icon {
          color: #409eff;
          font-size: 14px;
          display: inline-flex;
          align-items: center;
        }

        .video-name {
          color: #606266;
          font-size: 14px;
          line-height: 14px;
        }
      }
    }
  }

  .video-input-box {
    width: 100%;

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #dcdfe6 inset;

      &.is-disabled {
        box-shadow: 0 0 0 1px #e4e7ed inset;
        background-color: #f5f7fa;
      }
    }
  }
}

// 添加禁用状态的样式
:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
  cursor: not-allowed;
}

// 添加只读内容样式
.readonly-content {
  padding: 12px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 200px;
  width: 100%;
  overflow-y: auto;
  line-height: 1.5;
  color: #606266;

  :deep(p) {
    margin: 0;
    padding: 0;
  }

  :deep(img) {
    max-width: 100%;
  }
}

// 添加预览图片样式
.image-preview {
  width: 120px;
  height: 120px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.no-image {
  width: 120px;
  height: 120px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}

.video-preview-container {
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; // 16:9 比例
  position: relative;
  background-color: #000;

  .preview-video,
  .preview-iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: contain;
    border: none;
  }
}

.video-info {
  .el-button {
    padding: 4px 0;
    height: auto;
  }
}
</style>
